//
//  UserLoginVC.m
//  huien
//
//  Created by yiban on 2017/5/26.
//  Copyright © 2017年 lcb. All rights reserved.
//

#import "UserLoginVC.h"
#import "UserRegisterVC.h"
#import "UserPasswordVC.h"
#import "HEGestureManagerViewController.h"
#import "UserDepositVC.h"
@interface UserLoginVC ()<UITextFieldDelegate>
{
    
}
@property(nonatomic,strong) UITextField     *txtNickname;
@property(nonatomic,strong) UITextField     *txtPass;
@property(nonatomic,strong) UIButton     *loginBtn;
@property(nonatomic,strong) UIButton     *settingBtn;
@property(nonatomic,strong) UIButton     *registerBtn;
@property(nonatomic,strong) UIButton     *closeBtn;
@property(nonatomic,strong) UILabel *newLabel;
@property(nonatomic,strong) UIButton     *showBtn;
@end

@implementation UserLoginVC
@synthesize from=_from;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"用户登录";
    self.headerView.hidden = YES;
    [self initUI];
    UITapGestureRecognizer* singleRecognizer= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFrom)];
    self.view.userInteractionEnabled =YES;
    [self.view addGestureRecognizer:singleRecognizer];
    singleRecognizer=nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc
{
    self.txtNickname=nil;
    self.txtPass=nil;
    self.loginBtn=nil;
    self.settingBtn=nil;
    self.registerBtn=nil;
    [LcbLog log:@"UserLoginVC--------->dealloc"];
}
-(UILabel*)newLabel
{
    if (!_newLabel) {
        _newLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
        _newLabel.text = @"欢迎登录";
        _newLabel.font = [UIFont boldSystemFontOfSize:30];
        _newLabel.textColor = h1color;
        _newLabel.textAlignment = NSTextAlignmentCenter;
        _newLabel.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_newLabel];
    }
    return _newLabel;
}
-(UIButton*)closeBtn
{
    if (!_closeBtn) {
        _closeBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setImage:[UIImage imageNamed:@"icon_close"] forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_closeBtn];
    }
    return _closeBtn;
}

-(UIButton*)loginBtn
{
    if (!_loginBtn) {
        _loginBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.backgroundColor =btncolor;
        _loginBtn.layer.cornerRadius = 45/2;
        _loginBtn.tag=1;
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(loginbtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_loginBtn];
    }
    return _loginBtn;
}
-(UIButton*)registerBtn
{
    if (!_registerBtn) {
        _registerBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _registerBtn.backgroundColor =[UIColor clearColor];
        _registerBtn.tag= 3;
        _registerBtn.titleLabel.font =[UIFont systemFontOfSize:14];
        [_registerBtn setTitleColor:btncolor forState:UIControlStateNormal];
        [_registerBtn setTitle:@"立即注册" forState:UIControlStateNormal];
        _registerBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        [_registerBtn addTarget:self action:@selector(loginbtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_registerBtn];
    }
    return _registerBtn;
}
-(UIButton*)settingBtn
{
    if (!_settingBtn) {
        _settingBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _settingBtn.backgroundColor =[UIColor clearColor];
        _settingBtn.tag =2;
        _settingBtn.titleLabel.font =[UIFont systemFontOfSize:14];
        [_settingBtn setTitleColor:btncolor forState:UIControlStateNormal];
        [_settingBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
        _settingBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
        [_settingBtn addTarget:self action:@selector(loginbtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_settingBtn];
    }
    return _settingBtn;
}

-(UITextField *)txtNickname
{
    if (!_txtNickname) {
        _txtNickname = [[UITextField alloc] initWithFrame:CGRectZero];
        _txtNickname.placeholder = @"用户名／邮箱/ 手机号";
        _txtNickname.font = [UIFont systemFontOfSize:13];
        [_txtNickname setValue:h2color forKeyPath:@"_placeholderLabel.textColor"];
        _txtNickname.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtNickname.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _txtNickname.returnKeyType = UIReturnKeyNext;
        _txtNickname.clearButtonMode = UITextFieldViewModeWhileEditing;
        _txtNickname.delegate=self;
        _txtNickname.leftView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_phone"]];
        _txtNickname.leftViewMode=UITextFieldViewModeAlways; //此处用来设置leftview现实时机
        _txtNickname.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        
        [self.view addSubview:_txtNickname];
    }
    return _txtNickname;
}
-(UITextField *)txtPass
{
    if (!_txtPass) {
        _txtPass = [[UITextField alloc] initWithFrame:CGRectZero];
        _txtPass.placeholder = @"请输入密码";
        [_txtPass setValue:h2color forKeyPath:@"_placeholderLabel.textColor"];
        _txtPass.clearButtonMode = UITextFieldViewModeWhileEditing;
        _txtPass.font =[UIFont systemFontOfSize:13];
        _txtPass.secureTextEntry = YES;
        _txtPass.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtPass.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _txtPass.returnKeyType = UIReturnKeyGo;
        _txtPass.clearButtonMode = UITextFieldViewModeWhileEditing;
        _txtPass.delegate=self;

        _txtPass.leftView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_pwd"]];
        _txtPass.leftViewMode=UITextFieldViewModeAlways; //此处用来设置leftview现实时机
        _txtPass.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _txtPass.rightView = self.showBtn;
        _txtPass.rightViewMode=UITextFieldViewModeAlways;
        [self.view addSubview:_txtPass];
    }
    return _txtPass;
}
-(UIButton*)showBtn
{
    if (!_showBtn) {
        _showBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _showBtn.tag=0;
        [_showBtn setImage:[UIImage imageNamed:@"icon_pwhidden"] forState:UIControlStateNormal];
        [_showBtn setImage:[UIImage imageNamed:@"icon_pwshow"] forState:UIControlStateSelected];
        [_showBtn addTarget:self action:@selector(loginbtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_showBtn];
    }
    return _showBtn;
}
//按下Done按钮的调用方法，我们让键盘消失
-(void)handleSingleTapFrom
{
    if ([self.txtNickname isFirstResponder]) {
         [self.txtNickname resignFirstResponder];
    }
    if ([self.txtPass isFirstResponder]) {
         [self.txtPass resignFirstResponder];
    }
   
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField==self.txtNickname) {
        [self.txtPass becomeFirstResponder];
    }else  if (textField==self.txtPass){
        [self btnLoginAction];
        [textField resignFirstResponder];
    }else
    {
        [textField resignFirstResponder];
    }
    return YES;
}

-(void)initUI
{
    
    self.closeBtn.frame = CGRectMake(SCREEN_WIDTH -60, 20, 40, 40);
    //
    self.newLabel.frame = CGRectMake(0, 100, SCREEN_WIDTH, 40);
    //
    self.txtNickname.frame =CGRectMake(20, self.newLabel.frame.origin.y+self.newLabel.frame.size.height +80, SCREEN_WIDTH-40, 40);
    UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(0,self.txtNickname.height - 1, self.txtNickname.width, 1)];
    lineView1.backgroundColor = linecolor;
    [self.txtNickname addSubview:lineView1];
    self.txtPass.frame =CGRectMake(20, self.txtNickname.frame.origin.y+self.txtNickname.frame.size.height+15, SCREEN_WIDTH-40, 40);
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0,self.txtPass.height - 1, self.txtPass.width, 1)];
    lineView.backgroundColor = linecolor;
    [self.txtPass addSubview:lineView];
    //
    self.showBtn.frame=CGRectMake(0, 0, 32, 32);
    //
    self.loginBtn.frame =CGRectMake(20, self.txtPass.frame.origin.y+self.txtPass.frame.size.height+45, SCREEN_WIDTH-40, 45);
    //
    self.registerBtn.frame =CGRectMake(20, SCREEN_HEIGHT-40, (SCREEN_WIDTH-60)/2, 30);
    self.settingBtn.frame =CGRectMake(SCREEN_WIDTH - 100, SCREEN_HEIGHT-40, 80, 30);
}
-(void)clickNavEvent:(id)sender
{
    if(self.from!=1)
    {
        if ([_delegate respondsToSelector:@selector(userDidCancel)]) {
            [_delegate userDidCancel];
        } 
    }
    [[LcbCache sharedCache] removeObjectForKey:@"SessionModel"];
    [[LcbCache sharedCache] removeObjectForKey:@"sessionId"];
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count == 1) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)loginbtnClick:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            [self.txtPass setSecureTextEntry:self.showBtn.isSelected];
            [self.showBtn setSelected:!self.showBtn.isSelected];
        }
            break;
        case 1:
        {
            [self btnLoginAction];
        }
            break;
        case 2:
        {
            UserPasswordVC *reg =[UserPasswordVC newWithDelegate:_delegate];
            [self.navigationController pushViewController:reg animated:YES];
        }
            break;
        case 3:
        {
            UserRegisterVC *reg =[UserRegisterVC newWithDelegate:_delegate];
            [self.navigationController pushViewController:reg animated:YES];
        }
            break;

        default:
            break;
    }
}
- (void)btnLoginAction
{
    
    if(self.txtNickname.text.length==0)
    {
        [YBToast showWithText:@"请输入用户名"];
        return;
    }
    if(self.txtPass.text.length==0)
    {
        [YBToast showWithText:@"请输入用户密码"];
        return;
    }
    [self handleSingleTapFrom];
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:self.txtNickname.text forKey:@"userName"];
    [dict setValue:[self.txtPass.text md5String] forKey:@"password"];
    __weak typeof(self) weakSelf = self;
    [HEApi loginWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
        if (response) {
            if ([response isKindOfClass:[LcbBaseModel class]]) {
                LcbBaseModel *baseModel = (LcbBaseModel*)response;
                [[NativeRouter sharedNativeRouter] codeHander:weakSelf params:baseModel completion:nil];
            }else if ([response isKindOfClass:[SessionModel class]]) {
                SessionModel *sessionModel = (SessionModel*)response;
                [[LcbCache sharedCache] setObject:sessionModel forKey:@"SessionModel"];
                [[LcbCache sharedCache] setObject:weakSelf.txtNickname.text forKey:@"userName"];
                [[LcbCache sharedCache] setObject:[weakSelf.txtPass.text md5String] forKey:@"password"];
                [[JGShare sharedJGShare] setPushAlias:[NSString stringWithFormat:@"%ld",(long)sessionModel.session_user.userId]];
                [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%ld",(long)sessionModel.session_user.patternStatus] forKey:@"patternStatus"];
                [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%ld",(long)sessionModel.session_user.fingerprintStatus] forKey:@"fingerprintStatus"];
                [[NSUserDefaults standardUserDefaults] setValue:sessionModel.session_user.patternLock forKey:@"patternLock"];
                 [[NSUserDefaults standardUserDefaults] synchronize];
                if ([HEShare isGestureOpen]) {
                    if (sessionModel.session_user.customer_no.length==0) {
                        UserDepositVC *deposit =[UserDepositVC newWithDelegate:_delegate];
                        [weakSelf.navigationController pushViewController:deposit animated:YES];
                    }else{
                        if ([_delegate respondsToSelector:@selector(userLoginOK:)]) {
                            [_delegate userLoginOK:sessionModel];
                        }
                    }
                    
                }else{
                    HEGestureManagerViewController *gest =[HEGestureManagerViewController newWithDelegate:_delegate];
                    [weakSelf.navigationController pushViewController:gest animated:YES];
                }
                
            }
            
            
        }
        
    }];
    
}
@end
